package nl.avans.osgi.ds.persistence.person.data.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;

import nl.avans.osgi.ds.persistence.person.data.PersonService;
import nl.avans.osgi.ds.persistence.person.model.Person;

import org.eclipse.persistence.config.PersistenceUnitProperties;
import org.eclipse.persistence.jpa.osgi.PersistenceProvider;

public class PersonServiceImpl implements PersonService {
    private static final String PU_NAME = "persons";
    private EntityManagerFactory emf;
    private EntityManager em;

    @Override
    public Person getEmployee(long id) {
        // TODO Auto-generated method stub
        return null;
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Person> getEmployees() {
        System.out.println("PersonService: getEmployees");
        try {
            Query query = getEntityManager().createQuery("Select m from EMPLOYEE m");
            return query.getResultList();
        } catch (Exception e) {
            e.printStackTrace();
            return new ArrayList<Person>();
        }
    }

    private EntityManager getEntityManager() {
        if (em == null) {
            em = getEntityManagerFactory().createEntityManager();
        }
        return em;
    }

    private EntityManagerFactory getEntityManagerFactory() {
        if (emf == null) {
            HashMap<String, ClassLoader> properties = new HashMap<String, ClassLoader>();
            properties.put(PersistenceUnitProperties.CLASSLOADER, this.getClass().getClassLoader());
            emf = new PersistenceProvider().createEntityManagerFactory(
                    PU_NAME, 
                    properties);
        }
        return emf;
    }

    protected void activate() {
        System.out.println("PersonService activated.");
    }
    
    protected void deactivate() {
        System.out.println("PersonService deactivated.");
    }
    
}
